import { app, globalShortcut, BrowserWindow, ipcMain, dialog } from 'electron/main'
import os from 'os';
import { preloadPath } from '../config/index.js'
import checkUpdate from "../utils/updater.js";
import shortcutUpdate from "../utils/shortcutKeys.js";
import openNewView from "../utils/webview.js";
import chromiumVersion from "../utils/chromiumVersion.js";
import ChromeController from "../utils/ChromeController.js";
import downloadCore from "../utils/downloadCore.js";


import fs from 'fs'; // 从 Node.js 引入 fs 模块
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const packageJsonPath = path.join(__dirname, '../package.json'); // 假设 package.json 在上一级目录
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));

export const createWindow = opitons => {
  const win = new BrowserWindow({
    width: 1440,
    height: 900,
    minHeight: 900,
    minWidth: 1440,
    show: false,
    autoHideMenuBar: true, // 隐藏菜单栏
    webPreferences: {
      nodeIntegration: true, // 允许前端使用node
      preload: preloadPath,
    },
    ...opitons,
  })

  win.on('ready-to-show', () => {
    win.show()
    checkUpdate(win, ipcMain);
    shortcutUpdate(win, ipcMain);
    downloadCore(win, ipcMain)
    
    ipcMain.handle('open-webview', async (event, data) => {
      let a = JSON.parse(data)
      const controller = new ChromeController()
      await controller.launch(win,a)
      return true
    });

  })

  // win.webContents.openDevTools();


  return win
}

// 版本号
ipcMain.handle('get-version', () => {
  return app.getVersion();
});

// 退出软件
ipcMain.handle('window-all-closed', () => {
  app.quit();
});

ipcMain.handle('get-package', () => {
  let a = JSON.parse(JSON.stringify(packageJson))
  a.platform = process.platform
  return a;
});



ipcMain.handle('get-chromiums', async (event, data) => {
  return new Promise((resolve, reject) => {
    chromiumVersion().then((versionDirs) => {
      resolve(versionDirs)
    })
  });
});



const getMacAddress = () => {
  const interfaces = os.networkInterfaces();
  for (const name of Object.keys(interfaces)) {
    for (const iface of interfaces[name]) {
      if (iface.family === 'IPv4' && !iface.internal) {
        return iface.mac;
      }
    }
  }
  return null;
};

ipcMain.handle('get-mac-address', () => {
  return getMacAddress();
});



